#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import sys
import time
from subprocess import Popen
import asyncio
import websockets
from selenium import webdriver

from v2 import login
from v2 import robot

if __name__ == '__main__':
    '''初始化信息'''
    proxyName = 'mitmproxyV1.py'
    roomId = '26744536'  #懿懿
    # roomId = '106270448'  #霖纸

    # roomId = '139711992' #测试用   # 注意测试时 注释了  send 方法的调用！只做输出
    print('开始执行__init__')
    print('程序开始初始化...')

    print('执行代理程序')
    try:
        command = 'mitmdump -s {}'.format(proxyName)
        print('启动命令：' ,command)
        process = Popen(command)
    except Exception as e:
        print('启动代理失败!请检查代理脚本路径是否在当前启动程序目录下！')
        input("按任意键结束程序\n")
        print(e)
        sys.exit(1)  # 1表示异常退出， 0 正常退出

    print('执行代理成功')
    print('初始化webdriver')
    time.sleep(1) # 等待代理执行。
    option = webdriver.ChromeOptions()
    option.add_experimental_option('excludeSwitches', ['enable-automation'])
    # option.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2}) #不显示图片
    option.add_argument('disable-infobars')  # 浏览器不显示受自动测试软件控制
    # 设置代理
    option.add_argument("--proxy-server=http://127.0.0.1:8080")
    driver = webdriver.Chrome(options=option)
    print('请使用第三方登录')
    driver = login.login(None, None, driver)
    # 跳入直播页面
    driver.get('https://fm.missevan.com/live/%s' %roomId)
    print('初始化机器人')
    robot1 = robot.robot(driver)
    print('机器人初始化完毕')
    print('实例化保存机器人')
    date = datetime.datetime.now().strftime('%Y-%m-%d')
    name = 'robot{}.obj'.format(date)
    # 初始化ws服务器。
    async def recv_msg(websocket):
        while True:
            recv_text = await websocket.recv()
            print('接收到：', recv_text)
            response_text = f"your submit context: {recv_text}"
            robot1.route(recv_text)
            print(response_text)
    async def main_logic(websocket, path):
        try:
            await recv_msg(websocket)
        except websockets.exceptions.ConnectionClosedOK as e:
            print('短链接断开')
    start_server = websockets.serve(main_logic, '127.0.0.1', 8099)
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
    input("Press any key to exit\n")
